package mirfordevoservice.system.service;

import mirfordevoservice.system.service.Handler.ReqHandler;
import mirfordevoservice.system.GameCenter.DataCenter;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * Created by Heart!
 *
 * @Author ZhangChaoJian
 * @Date 2018/3/14.20:01
 * Wants More Then Try Hard More!
 */
public class MainService {
    private static MainService INSTANCE = new MainService();

    private MainService() {
    }

    public static MainService getINSTANCE() {
        return INSTANCE;
    }

    /**
     * 启动网络服务器
     *
     * @param client
     * @throws IOException
     */
    private static void invoke(final Socket client) throws IOException {
        new Thread(new Runnable() {
            public void run() {
                ObjectInputStream in = null;
                ObjectOutputStream out = null;
                try {
                    client.setTcpNoDelay(true);
                    client.setSoTimeout(0);
                    client.setKeepAlive(true);
                    in = new ObjectInputStream(client.getInputStream());
                    out = new ObjectOutputStream(client.getOutputStream());
                    while (true) {
                        ReqHandler.getINSTANCE().isHeartBeat(in, out, client);//开始处理事务
                        int curTime = (int) (System.currentTimeMillis() / 1000l);
                        if ((curTime - ReqHandler.lastTime) > 30000) {
                            client.close();
                            System.out.println("玩家长时间未连接，自动断线...");
                            DataCenter.getInstance().savingData();
                            return;
                        }
                        Thread.sleep(10);
                    }
                } catch (IOException ex) {
                    try {
                        DataCenter.getInstance().savingData();
                        System.out.println("玩家下线，执行下线逻辑...");
                        in.close();
                        out.close();
                        client.close();
                        return;
                    } catch (Exception e) {
                    }
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    public void startServer() throws IOException {
        ServerSocket server = new ServerSocket(9013);
        System.err.println("开启服务器成功，等待客户端接入...");
        while (true) {
            Socket socket = server.accept();
            System.out.println("新的链接进入:\n地址为:" + socket.getLocalAddress() + "\n端口为:" + socket.getLocalPort());
            invoke(socket);
        }
    }
}

